﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Cit.CDE.Net.Service.ModuleFactory;
using Cit.CDE.Net.Module;
using System.Collections.Generic;
using Cit.CDE.Net.Module.Commons;
using cde.SystemCommon;
using Cit.CDE.Net.Service;
using System.Text;

using Module;


/// <summary>
/// Copyright (C)   jinggubang
/// FileName:        LoreTypeEdit.aspx.cs           
/// Author :         wangbc
/// CDT:             2012-02-01           
/// Version:         1.0.0.0                
/// Depiction:       知识库分类新增    
/// </summary>
public partial class main_admin_LoreTypeEdit : UserControl.CommonPage
{
    /// <summary>
    /// 知识库分类EM
    /// </summary>
    private CDEEntityManager em;
    /// <summary>
    /// 知识库分类Entity
    /// </summary>
    private CDEEntity m_entity;
    /// <summary>
    /// 知识库分类Entity名字
    /// </summary>    
    private const string EM_FULL_NAME = WEBConstants.EM_LORETYPE_MANAGE;

    /// <summary>
    /// 页面初始化
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        //知识库分类ID
        string chkID = (string)Request.QueryString.Get("chkID");

        em = CDEEMFactory.getEMByFullName(EM_FULL_NAME);
        if (!Page.IsPostBack)
        {
            //ID不为空修改知识库分类，否则新增知识库分类
            if (chkID != "" && chkID != null)
            {
                //修改
                this.page_title.InnerText = "知识库分类修改";              
                CDESearchCriteria sc = new CDESearchCriteria(em);
                sc.addCondition("ID", chkID);
                List<CDEEntity> listEntity = CDEService.LoadEntities(em, sc);
                //知识库分类ID是否存在
                if (listEntity.Count > 0)
                {
                    m_entity = listEntity[0];
                    m_entity.Operation = CDEDataOperation.UPDATE;

                    string typeCode=Util.objectToString(m_entity.get("TYPE_CODE"));   
                    string level = Util.objectToString(m_entity.get("TYPE_LEVEL"));

                    int supCustomerIdNum = (int.Parse(level) - 1) * 2;
                    if (supCustomerIdNum > 0)
                    {
                        CDESearchCriteria scCheck = new CDESearchCriteria(em);
                        string scCode=Util.objectToString(typeCode).Substring(0, supCustomerIdNum).PadRight(8, '0');
                        scCheck.addCondition("TYPE_CODE", scCode);
                        scCheck.addSortOrder("TYPE_CODE");
                        scCheck.PageSize = 0;
                        List<CDEEntity> listCheck = CDEService.LoadEntities(em, scCheck);
                        this.lblUpLoreType.Text = listCheck[0].get("TYPE_NAME").ToString();                     
                    }

                    this.loreTypeV.Visible = false; 
                }
                else
                {
                    m_entity = CDEEMServiceFactory.getEMService(em).CreateEntity();
                    m_entity.Operation = CDEDataOperation.INSERT;
                }
            }
            else
            {
                //新增
                this.page_title.InnerText = "知识库分类新增";
                m_entity = CDEEMServiceFactory.getEMService(em).CreateEntity();
                m_entity.Operation = CDEDataOperation.INSERT;
                
            }
            Session["MENTITY"] = m_entity;
            //知识库分类信息设值到页面
            this.setControls(m_entity, Resources.ResourceErrMsg.ResourceManager);

            //修改时,类型不能修改
            if (chkID != "" && chkID != null)
            {
               
            }
        }
        else
        {
            m_entity = (CDEEntity)Session["MENTITY"];
            //页面信息放入知识库分类Entity
            this.setEntityFromRequest(m_entity, Request.Params);
        }     
    }
    /// <summary>
    /// 确定按钮
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void queding_Click(object sender, EventArgs e)
    {
        List<CDEEntity> listEntity = new List<CDEEntity>();
        listEntity.Add(m_entity);
        bool isSaveError = false;
        string chkID = (string)Request.QueryString.Get("chkID");
        CDESearchCriteria vsc = new CDESearchCriteria(em);
        //更新,否则新增
        if (chkID != null)
        {
            vsc.addCondition("ID", chkID, CDEConstCompare.Inequality);
        }       
        vsc.addCondition("TYPE_NAME", m_entity.get("TYPE_NAME"));
        List<CDEEntity> vListEntity = CDEService.LoadEntities(em, vsc);
        //知识库分类名称存在不执行更新,不存在执行更新
        if (vListEntity.Count > 0)
        {
            showMessageErrAndOk("该知识库分类标题已经存在！");
            isSaveError = true;
        }
        else
        {

            // 新增 时处理
            if (chkID == null)
            {
                //类型代码
                string type_code = "";
                string type_level = "";
                //一级分类
                string typecode1 = cutCodeFromCodeAndName(this.cddLoreType1.SelectedValue.ToString());
                //二级分类
                string typecode2 = cutCodeFromCodeAndName(this.cddLoreType2.SelectedValue.ToString());
                //三级分类
                string typecode3 = cutCodeFromCodeAndName(this.cddLoreType3.SelectedValue.ToString());

                //以选择的上级分类生成当前分类CODE
                if (typecode2 == "" && typecode1 == "" && typecode3 == "")
                {

                    type_code = this.getCustomerId("");
                    type_level = "1";
                }
                else
                {
                    //先检查上级是否为第二级
                    if (typecode3 != "")
                    {
                        type_code = this.getCustomerId(typecode3.Substring(0, 6));
                        type_level = "4";
                    }else if (typecode2 != "")
                    {
                        type_code = this.getCustomerId(typecode2.Substring(0, 4));
                        type_level = "3";
                    }else  if (typecode1 != "")
                    {
                        type_code = this.getCustomerId(typecode1.Substring(0,2));
                        type_level = "2";
                    } 
                }

                m_entity.set("TYPE_CODE",type_code);
                m_entity.set("TYPE_LEVEL", type_level);

            }

            CDEService.UpdateEntities(em, listEntity);

            if (listEntity[0].Result == CDEDataOperationResult.ERROR)
            {
                isSaveError = true;
            }
            else
            {
                isSaveError = false;
            }
        }

        //成功返回列表，失败提示错误信息
        if (isSaveError)
        {
            showMessageErrAndOk(Resources.ResourceErrMsg.SAVE_ERR);
            this.setControls(m_entity, Resources.ResourceErrMsg.ResourceManager);
        }
        else
        {

            StringBuilder sbr = new StringBuilder();
            sbr.AppendFormat("<script language=\"javascript\">{0}", Environment.NewLine);
            sbr.AppendFormat("alert(\"");
            sbr.AppendFormat(Resources.Resource.RESULT_OK);
            sbr.AppendFormat("\");window.location='../admin/LoreTypeList.aspx?EM=" + EM_FULL_NAME + "&sel_menu_id=" + Sel_MenuNode.Attributes["id"].Value + "&IsBackSc=1';</script>{0}", Environment.NewLine);
            Page.ClientScript.RegisterStartupScript(Page.GetType(), "Startup", sbr.ToString());
        }

    }
    /// <summary>
    /// 返回按钮
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void cmdCancel_Click(object sender, EventArgs e)
    {
        if (Sel_MenuNode == null)
            return;
        StringBuilder url = new StringBuilder();
        url.Append("../admin/LoreTypeList.aspx?EM=");
        url.Append(EM_FULL_NAME);
        url.Append("&sel_menu_id=");
        url.Append(Sel_MenuNode.Attributes["id"].Value);
        url.Append("&IsBackSc=1");
        Response.Redirect(url.ToString());

    }


    /// <summary>
    /// 把联动下拉单中的选择值处理一下只剩下code
    /// </summary>
    /// <param name="codeAndName">处理前</param>
    /// <returns>处理后</returns>
    protected string cutCodeFromCodeAndName(string codeAndName)
    {
        string result = "";
        int index = codeAndName.IndexOf(":");
        if (index > 0)
        {
            result = codeAndName.Substring(0, index);
        }
        return result;
    }

    /// <summary>
    /// 根据上级客户得到本次客户的ID
    /// </summary>
    /// <returns></returns>
    private string getCustomerId(string customerId)
    {

        CDESearchCriteria scCheck = new CDESearchCriteria(em);

        if (customerId.Length > 0)
        {
            scCheck.addCondition("TYPE_CODE", customerId, CDEConstCompare.LikeLeft);
        }
        else
        {
            scCheck.addCondition("CUSTOMER_LEVEL", "1", CDEConstCompare.Equality);
        }
        scCheck.addSortOrder("TYPE_CODE");

        scCheck.PageSize = 0;

        List<CDEEntity> listCheck = CDEService.LoadEntities(em, scCheck);

        if (listCheck.Count == 0)
        {
            customerId = "10000000";
        }
        else
        {
            string temp_customId = listCheck[listCheck.Count - 1].get("TYPE_CODE").ToString().Substring(0, customerId.Length + 2);
            string s = temp_customId.Substring(customerId.Length);

            customerId = (temp_customId.Substring(0, customerId.Length) + (float.Parse(s) + 1).ToString().PadLeft(2, '0')).PadRight(8, '0');

        }


        return customerId;
    }
}
